package com.mtk.launcher.util;

import android.os.SystemClock;
import android.view.MotionEvent;
import android.view.View;

public class ClickSimulator {

    // 获取单点点击事件序列（按下+抬起）
    public static void simulateClick(View view, float x, float y) {
        long downTime = SystemClock.uptimeMillis();
        long eventTime = SystemClock.uptimeMillis();

        // 按下事件
        MotionEvent downEvent = MotionEvent.obtain(
                downTime,
                eventTime,
                MotionEvent.ACTION_DOWN,
                x,
                y,
                0
        );

        // 抬起事件
        MotionEvent upEvent = MotionEvent.obtain(
                downTime,
                eventTime + 100, // 模拟100ms的点击时长
                MotionEvent.ACTION_UP,
                x,
                y,
                0
        );

        // 分发事件
        view.dispatchTouchEvent(downEvent);
        view.dispatchTouchEvent(upEvent);

        // 回收事件
        downEvent.recycle();
        upEvent.recycle();
    }

    // 模拟滑动事件
    public static void simulateSwipe(View view, float startX, float startY, float endX, float endY, int duration) {
        long downTime = SystemClock.uptimeMillis();
        long eventTime = downTime;

        // 计算滑动步数
        int steps = 10;
        float stepX = (endX - startX) / steps;
        float stepY = (endY - startY) / steps;
        long stepTime = duration / steps;

        // 按下事件
        MotionEvent downEvent = MotionEvent.obtain(
                downTime,
                eventTime,
                MotionEvent.ACTION_DOWN,
                startX,
                startY,
                0
        );
        view.dispatchTouchEvent(downEvent);

        // 移动事件
        for (int i = 1; i < steps; i++) {
            eventTime += stepTime;
            float x = startX + stepX * i;
            float y = startY + stepY * i;

            MotionEvent moveEvent = MotionEvent.obtain(
                    downTime,
                    eventTime,
                    MotionEvent.ACTION_MOVE,
                    x,
                    y,
                    0
            );
            view.dispatchTouchEvent(moveEvent);
            moveEvent.recycle();
        }

        // 抬起事件
        eventTime += stepTime;
        MotionEvent upEvent = MotionEvent.obtain(
                downTime,
                eventTime,
                MotionEvent.ACTION_UP,
                endX,
                endY,
                0
        );
        view.dispatchTouchEvent(upEvent);

        // 回收事件
        downEvent.recycle();
        upEvent.recycle();
    }
}